package javax;

/**
 * Created by xupeng20 on 2019/1/13.
 */

//仓库类
public class Xp_0118 {
    /**
     * 多线程（生产者消费者模型）
     */
    //仓库容量
    private final int MAX_SIZE;
    //当前货物数量
    private int count;
    public Xp_0118(int n){
            MAX_SIZE =n;
            count=0;
    }
    public synchronized void add(){
        while (count>=MAX_SIZE){
            System.out.println("满了");
            try{
                this.wait();
            }catch (Exception e){}
        }
        count++;
        //唤醒一个等待的线程
        this.notify();
        System.out.println(Thread.currentThread().toString()+"put"+count);
    }
    public synchronized void remove(){
        while (count<0){
            System.out.println("没了");
            try{
                this.wait();
            }catch (Exception e){}
        }
        count--;
        this.notify();
        System.out.println(Thread.currentThread().toString()+"get"+count);
    }
     static class Producer extends Thread{
        private Xp_0118 xp;
        public Producer(Xp_0118 xp){
            this.xp=xp;
        }
        @Override
        public void run(){
            while (true){
                xp.add();
                try {
                    Thread.sleep(1000);
                } catch (Exception e){}
            }
        }
    }
    static class Consumer extends Thread{
        private Xp_0118 xp;
        public Consumer(Xp_0118 xp){
            this.xp=xp;
        }
        @Override
        public void run(){
            while (true){
                xp.remove();
                try {
                    Thread.sleep(1500);
                } catch (Exception e){}
            }
        }
    }
    public static void main(String[] args){
        Xp_0118 xp = new Xp_0118(3);
        Thread p1 = new Producer(xp);
        Thread c1 = new Consumer(xp);
        Thread p2 = new Producer(xp);
        Thread c2 = new Consumer(xp);
        p1.setName("p11111");
        p2.setName("p22222");
        c1.setName("c11111");
        p2.setName("c22222");
        p1.start();
        p2.start();
        c1.start();
        c2.start();
    }
}
